package com.youtills.view;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * TODO - !!!doc me!!!
 *
 * @author ravi.chiluveru
 * @since 1.0 (7/19/14)
 */
public class ResourceDispatcherServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        final String path = req.getServletPath();

        if(isMediaItem(path)) {
            forwardToDefault(req, resp, getServletContext());
        } else {
            com.youtills.view.RequestDispatcher.dispatch(req, resp);
        }
    }
    private static boolean isMediaItem(String path){
        if(path != null){
            String lPath = path.toLowerCase();
            return lPath.endsWith(".css")
                    || lPath.endsWith(".jpg")
                    || lPath.endsWith(".gif")
                    || lPath.endsWith(".png")
                    || lPath.endsWith(".action")
                    || lPath.endsWith(".ico")
                    || lPath.endsWith(".js");
        }

        return false;
    }

    private static void forwardToDefault(HttpServletRequest req, HttpServletResponse resp, ServletContext context) throws IOException, ServletException {
        javax.servlet.RequestDispatcher rd = context.getNamedDispatcher("default");

        HttpServletRequest wrapped = new HttpServletRequestWrapper(req);

        rd.forward(wrapped, resp);
    }

}
